package com.kfm.dbutils.dao;

import com.kfm.dbutils.model.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

@Repository
public class UserDao {

    @Autowired
    private QueryRunner queryRunner;


    public List<User> selectAll() throws SQLException {
        String sql = "select * from user";
        List<User> query = queryRunner.query(sql, new BeanListHandler<>(User.class));
        return query;
    }

    public User selectById(Integer id) throws SQLException {
        String sql = "select * from user where id = ?";
//        ResultSetHandler<User> handler = new ResultSetHandler<User>() {
//            @Override
//            public User handle(ResultSet rs) throws SQLException {
//                if (!rs.next())
//                    return null;
//
//                User user = new User();
//                user.setId(rs.getInt("id"));
//                user.setUsername(rs.getString("username"));
//                user.setPassword(rs.getString("password"));
//                user.setName(rs.getString("name"));
//                user.setAvatar(rs.getString("avatar"));
//
//                return user;
//            }
//        };
        return queryRunner.query(sql, new BeanHandler<>(User.class), id);
    }


}

